<script setup>
import {ref, onMounted, computed} from 'vue'
import { sessionApi, pageNoteApi, procNotesApi, readNoteApi, oneNoteApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import Pager from '@/components/pagination/UbtPager.vue'
import { formatDate } from '@/common/filter'
import Datepicker from '@vuepic/vue-datepicker'
import '@vuepic/vue-datepicker/dist/main.css'

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

let userId = ''
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if (res.code === 200) {
    userId = res.data.userId
    list(0, 1)
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const dates = ref([])
const schObj = {
  schName: '',
  userId: userId,
  beginTime: 0,
  endTime: 0,
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const noteList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  schRef.value.beginTime = dates.value && dates.value.length===2 && dates.value[0] ? dates.value[0].getTime()/1000 : 0
  schRef.value.endTime = dates.value && dates.value.length===2 && dates.value[1] ? dates.value[1].getTime()/1000 : 0
  const res = await pageNoteApi(schRef.value)
  if(res.code === 200 && res.data) {
    hasData.value = true
    total.value = res.data.total
    noteList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    schName: '',
    userId: userId,
    beginTime: 0,
    endTime: 0,
    offset: 0,
    limit: 20
  }
  dates.value = []
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    noteList.value.forEach(item => {
      idList.value.push(item.rnuId)
      checkList.value.push(true)
    })
  } else {
    noteList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, rnuId) => {
  if(!checkList.value[idx]) {
    idList.value.push(rnuId)
  } else {
    const index = idList.value.findIndex(id => {
      if (id === rnuId) {
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

// detail 消息详情
const noteObj = {
  noteId: '',
  title: '',
  contents: '',
  addTime: 0
}
const noteRef = ref(noteObj)
const showModal = ref(false)
// readNote 已读消息
const readNote = async (rnuId, noteId) => {
  const res = await readNoteApi({ rnuId })
  if(res.code === 200) {
    detail(noteId)
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}
const detail = async (noteId) => {
  const res = await oneNoteApi({ noteId })
  if(res.code === 200 && res.data) {
    noteRef.value = res.data
    showModal.value = true
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  list(0, 1)
  showModal.value = false
  noteRef.value = null
}

// process 删除消息
const process = (states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要处理选中的消息吗？').then(() => {
    procNotes(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的消息！" })
  })
}
// procNotes 删除消息实现，分离出来防止调用时异步报错
const procNotes = async (states) => {
  const rnuIds = idList.value.join(',')
  const res = await procNotesApi({ states, rnuIds })
  if(res.code === 200) {
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，消息处理成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time, kind) => {
    let date = new Date(time*1000)
    return formatDate(date, kind)
  }
})
const dtRangeFmt = (date) => {
  if(date && date.length===2) {
    const beginDate = date[0]
    const endDate = date[1]
    const begins = beginDate.getFullYear() + "-" + (beginDate.getMonth()+1) + "-" + beginDate.getDate()
    const ends = endDate.getFullYear() + "-" + (endDate.getMonth()+1) + "-" + endDate.getDate()
    return `${begins} ~ ${ends}`
  }
  return ""
}

// stateFmt 状态转码
const stateFmt = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '未读'
        break;
      case 2:
        str = '已读'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="a">
    <!-- 头部消息 -->
    <div class="b">
      <div class="btn-p" title="已读" @click="process(2)"><i class="iconfont text_badge_checkmark"></i> 已读</div>
      <div class="btn-d" title="删除" @click="process(3)"><i class="iconfont trash"></i> 删除</div>
      <div class="btn-r" title="筛选" @click="search()"><i class="iconfont search"></i></div>
      <div class="btn-r" title="刷新" @click="list(0, 1)"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部数据 -->
    <div class="c" v-if="schShow">
      <div class="d"><input type="text" v-model="schRef.schName" placeholder="请输入名称或编码的关键字" class="e" /></div>
      <div class="d"><Datepicker v-model="dates" range locale="zh-CN" :format="dtRangeFmt" style="width: 250px;" placeholder="请选择起止时间"></Datepicker></div>
      <div class="btn-p" @click="list(0, 1)"><i class="iconfont search"></i> 筛选</div>
      <div class="btn-d" @click="clrSch()"><i class="iconfont arrowshape_turn_up_left"></i> 重置</div>
    </div>
    <div class="f" v-if="hasData">
      <table>
        <tr>
          <th style="width: 10%;"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></th>
          <th style="width: 50%;">标题</th>
          <th style="width: 25%;">时间</th>
          <th style="width: 15%;">状态</th>
        </tr>
        <tr v-for="(curNote, index) in noteList" :key="curNote.rnuId" class="tr-style">
          <td class="txt-center"><i @click="checkCurId(index, curNote.rnuId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></td>
          <td><a href="javascript:void(0);" class="cl-blue" @click="readNote(curNote.rnuId, curNote.noteId)">{{curNote.title}}</a></td>
          <td class="txt-center">{{fmtDate(curNote.addTime, 2)}}</td>
          <td class="txt-center">{{stateFmt(curNote.states)}}</td>
        </tr>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 800px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_text fs20"></i> 消息详情</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title">消息标题</div>
                <div class="g">{{noteRef.title}}</div>
              </div>
              <div>
                <div class="ipt-title">消息内容</div>
                <div class="g">{{noteRef.contents}}</div>
              </div>
              <div>
                <div class="ipt-title">发布时间</div>
                <div class="g">{{fmtDate(noteRef.addTime)}}</div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="closeModal()"><i class="iconfont today_fill"></i> 关闭</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {margin: 0 10px 10px 10px; border: 1px solid #CCC; display: flex; display: -webkit-flex; flex-wrap: wrap; justify-content: flex-end; padding: 15px;}
.d {flex-grow: 1;}
.e {width: 230px; padding: 8px;}
.f {background-color: #FFF;}
.g {padding: 5px 20px;}
</style>
